#include "Command.h"
#include <stdio.h>
#include <stdlib.h>

Command::Command()
{
	m_type = SSpawn;
	m_gameNumber = -1;
	m_value = 0;
	sprintf_s(m_string, "");
}

//load the buffer for sending
//done only in comm
void Command::Pack(char* buffer)
{
			//type#value#string#
	sprintf_s(buffer, DEFAULT_BUFLEN*sizeof(char), "%i#%i#%s#", m_type, m_value, m_string);
}

//unload the sent buffer and fill variables
//done only in comm
void Command::unPack(char* data)
{
	char stop = '#', *p = &stop , temp[DEFAULT_BUFLEN];
	int counter=0;

	//command type
	counter += ParseString(counter, temp, data, stop);
	m_type = (CMD_TYPE)strtol(temp, &p, 10);
	
	//value
	counter += ParseString(counter, temp, data, stop);
	m_value = strtol(temp, &p, 10);
	
	//string
	counter += ParseString(counter, temp, data, stop);
	sprintf_s(m_string, "%s", temp);
}

int Command::ParseString(int start, char* buffer, char* data, char stop)
{
	char cursor = data[start];
	if(cursor == stop)
	{
		buffer[0] = '\0';
		return 1;
	}
	int i=0;

	//weirdest for loop evar!!
	for(start; cursor != stop; start++, ++i)
	{
		cursor = data[start];
		buffer[i] = cursor;
	}
	buffer[i-1] = '\0';

	return i;
}

//fill command variables
//done at "far ends"	Client_IO and GameState
void Command::encode(CMD_TYPE a_type, int a_value, char* a_string)
{
	m_type = a_type;
	m_value = a_value;
	sprintf_s(m_string, "%s", a_string);
}